import { _decorator, Component, Node, Vec2, ProgressBar, Label, Vec3, AudioClip, AudioSource, instantiate, PolygonCollider2D, Contact2DType, Collider2D } from 'cc';
import { Battle } from '../../Battle';
import { EnDynamicLineType } from '../../Common/const/EnCommon';
import { EnEvent } from '../../Common/const/EnEvent';
import { GameAPI } from '../../Common/GameAPI';
import { Enum_AudioClip, Enum_ColliderGroup } from '../../Enum';
import { PlayerEnergyManager } from '../../Player/PlayerEnergyManager';
import { ResourcesUtil } from '../../ResourcesUtil';
import { EnergyUseController } from '../EnergyUseController';
import { NumberSplitter } from '../NumberSplitter';
import { TowerManager } from './TowerManager';
const { ccclass, property } = _decorator;

@ccclass('TowerController')
export class TowerController extends Component {

    @property(Node)
    public noneTower: Node = null;
    @property(Node)
    public heroTowerNode: Node = null;
    @property(Node)
    public hero1Node: Node = null;
    @property(Node)
    public hero2Node: Node = null;
    @property(Node)
    public hero3Node: Node = null;
    @property(Node)
    private energyUseNode: Node = null;

    private isCreateWait: boolean = true;
    private levelEnergyValues: Array<number> = [];
    private curLevel: number = -1;
    private curRequiredNum: number = 0;
    private maxLevel: number = 3;

    private levelLabelNum: Label;
    private towerId: number;
    private towerMagr: TowerManager;
    private levelNum: Node = null;
    private levelProgress: ProgressBar = null;
    private needEnergyType: number = 1;

    private waitTime: number = 0.2;
    private curWaitTime: number = 1;

    private isCanConstruct: boolean = false;

    public _audioSound: AudioSource;
    public _levelUpAudio: AudioClip = null;

    private collider: PolygonCollider2D;
    private isFeeding: boolean = false;
    private isUpgradeTower: boolean = false;

    private towerNode: Node;
    private energyManager: PlayerEnergyManager;
    private mumSplitter: NumberSplitter;
    public numNode: Node;

    async onLoad(): Promise<void> {
        this.numNode = this.node.getChildByName("NumNode");
        this._levelUpAudio = await ResourcesUtil.loadAudioClip(Enum_AudioClip.LevelUp);
    }

    start() {
        this.levelEnergyValues.push(5);
        this.levelEnergyValues.push(15);
        this.levelEnergyValues.push(35);

        this.maxLevel = this.levelEnergyValues.length;
        // this.levelNum = this.noneTower.getChildByName("Num");
        this.mumSplitter = this.numNode.getComponent(NumberSplitter);
        // this.levelLabelNum = this.levelNum.getComponent(Label);
        this.levelProgress = this.noneTower.getChildByName("ProgressBar").getComponent(ProgressBar);

        this._audioSound = this.node.getComponent(AudioSource);
        this.UpgradeTower();

        let myThis = this;
        // this.schedule(function () {
        //     myThis.UpdateLevelProgress();
        // }.bind(this), 0.05);

        this.towerNode = this.heroTowerNode.getChildByName("Tower");
        this.hero1Node.active = false;
        this.towerNode.active = false;

        // 碰撞监听
        this.collider = this.node.getComponent(PolygonCollider2D);
        if (this.collider) {
            this.collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
            this.collider.on(Contact2DType.END_CONTACT, this.onEndContact, this);
        }
        this.energyManager = Battle.playerNode.getComponent(PlayerEnergyManager);
    }



    // 碰撞开始回调
    onBeginContact(self: Collider2D, other: Collider2D) {
        // 碰到主角
        if (other.node.name.includes("Player")) {
            if (!this.isFeeding) {
                this.isUpgradeTower = false;
                let myThis = this;
                this.schedule(function () {
                    myThis.UpdateLevelProgress();
                }.bind(this), 0.05);
                this.isFeeding = true;
            }
        }
    }


    update() {
        this.numNode.active = this.noneTower.active;
    }

    //>=0表示可升级
    GetHowManyNum() {
        if (this.energyManager) {
            let energyNum = this.energyManager.GetEnergyNumByType(this.needEnergyType);
            return energyNum - this.curRequiredNum;
        }
        else {
            return -1;
        }
    }

    // 碰撞结束回调
    onEndContact() {
        this.isFeeding = false;
        if (!this.isUpgradeTower) {
            this.unscheduleAllCallbacks();
        }
    }

    onEnable() {
        this.waitTime = 1;
        this.isCanConstruct = true;
    }

    OnInit(mgr, id) {
        this.towerId = id;
        this.towerMagr = mgr;
        this.curLevel = -1;
        this.isCanConstruct = false;
    }

    CreatorItem() {
        let obj = instantiate(this.energyUseNode);
        this.node.addChild(obj);
        let useNode = this.node.getChildByName("EnergyUse");
        let controller = obj.getComponent(EnergyUseController);
        if (this.curLevel < 1) {
            controller.distance = 100;
        }
        else {
            useNode = this.node.getChildByName("EnergyUse2");
            controller.distance = 200;
        }
        obj.setScale(new Vec3(0.5, 0.5, 1));
        obj.setPosition(useNode.position);
        obj.active = true;
        obj.name = "flyUseItem";
    }

    // update(deltaTime: number) {
    // }

    UpdateLevelProgress() {
        if (this.curLevel >= this.maxLevel) {
            this.noneTower.active = false;
            this.numNode.active = false;
            return;
        }
        else if (this.noneTower.active == false) {
            return;
        }
        let energyNum = this.energyManager.GetEnergyNumByType(this.needEnergyType);
        if (energyNum > 0) {
            this.energyManager.RemoveEnergyNumByType(this.needEnergyType);
            this.curRequiredNum -= 1;
            if (this.curRequiredNum <= 0) {
                //塔升级
                this.noneTower.active = false;
                this.numNode.active = false;
                this.unscheduleAllCallbacks();
                this.UpgradeTower();
            }
            else {
                this.CreatorItem();
                this.UpdateProgressBar();
            }
        }

        // let playerWorldPos = Battle.playerNode.getWorldPosition();
        // let distance = Vec2.distance(this.node.getWorldPosition(), playerWorldPos);
        // let maxDistance = 100;
        // if (this.curLevel > 0) {
        //     maxDistance = 150;
        // }

        // if (this.isCanConstruct) {
        //     if (distance <= maxDistance) {
        //         let energyNum = Battle.playerNode.getComponent(PlayerEnergyManager).GetEnergyNum(this.needEnergyType);
        //         if (energyNum > 0) {
        //             this.curRequiredNum -= 1;
        //             if (this.curRequiredNum <= 0) {
        //                 //塔升级
        //                 this.noneTower.active = false;
        //                 this.UpgradeTower();
        //             }
        //             else {
        //                 this.CreatorItem();
        //                 this.UpdateProgressBar();
        //             }
        //         }
        //     }
        //     else {
        //         this.curWaitTime = this.waitTime;
        //     }
        // }
        // else {
        //     this.curWaitTime = this.curWaitTime - 0.1;
        //     if (this.curWaitTime <= 0) {
        //         this.isCanConstruct = true;
        //         this.curWaitTime = this.waitTime;
        //     }
        // }
    }

    UpgradeTower() {
        if (this.towerMagr == null) {
            return;
        }
        this.isCanConstruct = false;
        this.curLevel++;
        if (this.curLevel < this.maxLevel) {
            this.curRequiredNum = this.levelEnergyValues[this.curLevel];
            // this.levelLabelNum.string = 0 + "/" + this.curRequiredNum;
            // this.levelLabelNum.string = "x" + this.curRequiredNum.toString();
            this.mumSplitter.setNumber(this.curRequiredNum);
        }
        this.levelProgress.progress = 0;
        this.towerMagr.UpdateLevel(this.towerId, this.curLevel);
        if (this.curLevel > 0) {
            this.isUpgradeTower = true;
            let icon = this.noneTower.getChildByName("Icon");
            icon.active = false;
            // this.noneTower.setScale(new Vec3(3.5, 3.5, 3.5));
            GameAPI.FireGEvent(EnEvent.DynamicLineEvent, { type: EnDynamicLineType.Default });
            GameAPI.FireGEvent(EnEvent.CreateEffectEvent, { effectName: "Spell_Active_BlessKing", position: new Vec3(0, -110, 0), scale: new Vec3(2, 2, 2), parentNode: this.node });
            let myThis = this;
            this.scheduleOnce(function () {
                this.towerNode.active = true;
                this.numNode.active = true;
                let heroParentNode = myThis.heroTowerNode.getChildByName("Node");
                let heroNode = heroParentNode.getChildByName("Hero" + myThis.curLevel);
                if (heroNode) {
                    heroNode.active = true;
                }
                myThis.curWaitTime = 5;
                myThis._audioSound.playOneShot(myThis._levelUpAudio);
            }.bind(this), 0.01);
            GameAPI.FireGEvent(EnEvent.GuideTipEvent, { index: 3, active: false });
            if (this.curLevel > 1) {
                GameAPI.FireGEvent(EnEvent.GuideTipEvent, { index: 5, active: false });
            }
            if (this.node.name == "Tower1") {
                GameAPI.FireGEvent(EnEvent.AddPolygonEvent, { name: "Obstacle4" });
            }
            else if (this.node.name == "Tower2") {
                GameAPI.FireGEvent(EnEvent.AddPolygonEvent, { name: "Obstacle5" });
            }
            else if (this.node.name == "Tower3") {
                GameAPI.FireGEvent(EnEvent.AddPolygonEvent, { name: "Obstacle3" });
            }
            else if (this.node.name == "Tower4") {
                GameAPI.FireGEvent(EnEvent.AddPolygonEvent, { name: "Obstacle2" });
            }
        }
        else {
            // this.noneTower.setScale(new Vec3(1.5, 1.5, 1.5));
        }
        if (this.curLevel == 1) {
            this.hero1Node.position = new Vec3(13, 0, 0);
        }
        else if (this.curLevel == 2) {
            this.hero1Node.position = new Vec3(-28, 0, 0);
            this.hero2Node.position = new Vec3(52, 0, 0);
        }
        else if (this.curLevel == 3) {
            this.hero1Node.position = new Vec3(-28, 0, 0);
            this.hero2Node.position = new Vec3(52, 0, 0);
            this.hero3Node.position = new Vec3(11, -20, 0);
        }
        if (this.curLevel >= this.maxLevel) {
            this.noneTower.active = false;
            this.numNode.active = false;
        }
    }

    UpdateProgressBar() {
        // let total = this.levelEnergyValues[this.curLevel];
        // let progress = total - this.curRequiredNum;
        // this.levelLabelNum.string = progress + "/" + total;
        // this.levelLabelNum.string = "x" + this.curRequiredNum.toString();
        // this.levelProgress.progress = progress / total;
        this.mumSplitter.setNumber(this.curRequiredNum);
    }

    CreateWaitReset() {
        this.isCreateWait = false;
    }

}


